package com.cmcc.pcap.jpcap.tcp.tcp.xdr;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.cmcc.pcap.jpcap.tcp.TcpConnection;
import com.cmcc.pcap.jpcap.tcp.TcpPacketDecorator;
import com.cmcc.pcap.jpcap.util.DateUtil;
import com.cmcc.pcap.packet.util.PacketAnalysisConfig;
import com.cmcc.packet.entity.TcpEntity;

import jpcap.packet.TCPPacket;

public class TcpXdrGenerate {
	private static Logger logger = LogManager.getLogger(TcpXdrGenerate.class);
	public List<TcpEntity> generate(TcpConnection tcpConnection,String taskId) {
		List<TcpEntity> xdrtcpEntityList = new ArrayList<TcpEntity>();
		//TcpConnection tcpConnection = httpTransaction.tcpConnection;
		
		logger.debug("this is tcp xdr generate !");
		TcpEntity xdrtcpEntity = new TcpEntity();
		xdrtcpEntity.setTaskId(Integer.parseInt(taskId));
		xdrtcpEntity.setType("TCP");
		
		//调用业务识别模块需要传入前8个带数据的TcpPacketDecorator
		tcpConnection.reOrderTcpPacket2();
		ArrayList<TCPPacket> altemp = new ArrayList<TCPPacket>();
		Integer altemp_length = 0;
		for(TcpPacketDecorator tpd:tcpConnection.al){
			if(tpd.getData(1)!= null){
				altemp.add(tpd.tcpPacket);
				++altemp_length;
			}
			if(altemp_length == 8)
				break;
		}

		xdrtcpEntity.setTCPPackets(altemp);
		
	
		try {
			saveHttpsTcpConnectionToHttpsEntityList(tcpConnection,xdrtcpEntity);
		} catch (ParseException e) {
			logger.error(e.getCause(), e);
		}
		
		//将每个httpEntity加入httpEntityList中，调用SaveHttpTransactionInfo的save方法保存到数据库中
		xdrtcpEntityList.add(xdrtcpEntity);
		
		/**
		 * Interface
		 * ProcedureStartTime
		 * ProcedureEndTime
		 * ProtocolType
		 * AppType
		 * AppSubType
		 * IPAddressType
		 * UserIPv4
		 * UserIPv6
		 * ......
		 * 
		 * 
		 */
		return xdrtcpEntityList;
	}
	
	public void saveHttpsTcpConnectionToHttpsEntityList(TcpConnection tcpConnection,TcpEntity xdrtcpEntity) throws ParseException{
		
		int length = tcpConnection.al.size();
		logger.debug("tcpConnection length:"+length);
		
		TcpPacketDecorator tpdStart = tcpConnection.al.get(0);
		TcpPacketDecorator tpdEnd = tcpConnection.al.get(length-1);		
		
		//计算procedure_start_time
		long timestamp_procedure_start_time = tpdStart.tcpPacket.sec*1000 + tpdStart.tcpPacket.usec;
		Date procedureStartTime = DateUtil.formatTimestamp(timestamp_procedure_start_time);
		xdrtcpEntity.setProcedureStartTime(procedureStartTime);
				
		//计算procedure_end_time
		long timestamp_procedure_end_time = tpdEnd.tcpPacket.sec*1000 + tpdEnd.tcpPacket.usec;
		Date procedureEndTime = DateUtil.formatTimestamp(timestamp_procedure_end_time);
		xdrtcpEntity.setProcedureEndTime(procedureEndTime);
		
		//填写interface
		Integer interFace = 11;
		xdrtcpEntity.setInterfaceCode(interFace);
		
		//填写ip_address_type,ipv4是0,ipv6是1
		xdrtcpEntity.setIpAddressType(0);
				
		//填写终端用户的ipv4地址
		String userIpv4 = tpdStart.tcpPacket.src_ip.toString();
		userIpv4 = userIpv4.replace("/", "");
		xdrtcpEntity.setUserIpv4(userIpv4);
				
		//填写终端用户ipv6地址
		String userIpv6 = tpdStart.tcpPacket.src_ip.toString();
		xdrtcpEntity.setUserIpv6(userIpv6);
					
		//填写终端用户port
		Integer userPort = tpdStart.tcpPacket.src_port;
		xdrtcpEntity.setUserPort(userPort);
					
		//填写L4 Protocol,0为tcp,1为udp
		xdrtcpEntity.setL4Protocal(0);
		
		//填写服务端ipv4地址
		String appServerIpIpv4 = tpdStart.tcpPacket.dst_ip.toString();
		appServerIpIpv4 = appServerIpIpv4.replace("/", "");
		xdrtcpEntity.setAppServerIpIpv4(appServerIpIpv4);
					
		//填写服务端ipv6地址
		String appServerIpIpv6 = tpdStart.tcpPacket.dst_ip.toString();
		xdrtcpEntity.setAppServerIpIpv6(appServerIpIpv6);
					
		//填写服务端port
		Integer appServerPort = tpdStart.tcpPacket.dst_port;
		xdrtcpEntity.setAppServerPort(appServerPort);

		//填写payload
        //控制拿到payload的报文个数
        /* 
         * 从配置文件中拿payload个数
         */
        int payloadNum = PacketAnalysisConfig.getConfigAsInt("tcp.payloads.num");
        byte[] payloads = new byte[]{};
        
        /*
         * 根据配置文件，控制拿payload的个数
         */
        int getPayloadLength;
        if(payloadNum < tcpConnection.al.size())
        	getPayloadLength = payloadNum;
        else
        	getPayloadLength = tcpConnection.al.size();
        
        for(int i=0; i<getPayloadLength; i++) {
        	byte[] temp = tcpConnection.al.get(0).tcpPacket.data;
        	byte[] c = new byte[payloads.length+temp.length];
        	System.arraycopy(payloads, 0, c, 0, payloads.length);
        	System.arraycopy(temp, 0, c, payloads.length, temp.length);
        	payloads = c;
        }
		//将二进制数组转为16进制字符串
		StringBuilder payloadstr = new StringBuilder(payloads.length*2);
		for(byte b:payloads){
			payloadstr.append(String.format("%02x",new Integer(b & 0xff)));
		}
        xdrtcpEntity.setPayload(payloadstr);
        xdrtcpEntity.setPayloadLength(payloadstr.length());

		
		
	}
}